<template>
    <div>
        <el-row>
            <!-- 班级列表信息 -->
            <el-col :span="5">
                <h2 style="text-align: center;">班级列表</h2>
                <!-- 列表数据展示 ，label控制要展示的字段数据-->
                <el-tree :data="classesList" :props="{
                    label: 'className',
                }" highlight-current="true" @node-click="handleNodeClick" ref="classRef" node-key="classId"></el-tree>
            </el-col>

            <!-- 学生信息 -->
            <el-col :span="18" :offset="1">
                <!-- 信息查询 -->
                <el-form ref="queryFormRef" :model="queryForm" inline size="mini">
                    <el-form-item label="学号" prop="stuNum">
                        <el-input v-model="queryForm.stuNum"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="stuName">
                        <el-input v-model="queryForm.stuName"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phoneNum">
                        <el-input v-model="queryForm.phoneNum"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button type="info" @click="resetForm('queryForm'), getListStudent()">重置</el-button>
                    </el-form-item>
                </el-form>

                <!-- 添加 -->
                <el-row>
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
                </el-row>

                <!-- 表格 -->
                <el-table :data="studentList" style="width:100%">
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column prop="stuNum" label="学号" align="center" width="80" show-overflow-tooltip
                        fixed></el-table-column>
                    <el-table-column prop="stuName" label="姓名" align="center" width="80" fixed
                        show-overflow-tooltip></el-table-column>
                    <el-table-column prop="majorId" label="专业" align="center" width="110" show-overflow-tooltip>
                        <!-- 默认插槽：调用获取专业名称的函数 -->
                        <template #default="{ row }">
                            {{ getMajorName(row.majorId) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机" align="center" width="110"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column prop="age" label="年龄" align="center" width="50"></el-table-column>
                    <el-table-column prop="sex" label="性别" align="center" width="50">
                        <template #default="{ row }">
                            {{ getSexLabel(row.sex) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" align="center" width="160"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column prop="updateTime" label="修改时间" align="center" width="160"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column label="操作" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="text" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="text" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <el-row type="flex" justify="center">
                    <!-- .sync类似v-model，实现页面数据双向响应式 -->
                    <el-pagination layout="prev, pager, next" :total="pageIniation.total"
                        :page-size="pageIniation.pageSize" :current-page.sync="pageIniation.pageNum"
                        @current-change="getListStudent">
                    </el-pagination>
                </el-row>

                <!-- 弹窗 -->
                <!-- sync用来实现组件之间的数据双向流 -->
                <el-dialog :visible.sync="dialog.visible" width="400px" @close="resetForm('dialogForm')">
                    <template #title>{{ dialog.mode === "add" ? "添加学生" : "编辑学生信息" }}</template>
                    <el-form :model="dialog.form" label-width="100px" label-position="top" size="small"
                        :rules="dialog.rules" ref="dialogFormRef">
                        <el-form-item label="班级" prop="classId">
                            <el-select :value="dialog.form.classId" disabled>
                                <el-option v-for="item in classesList" :key="item.classId" :label="item.className"
                                    :value="item.classId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="姓名" prop="stuName">
                            <el-input v-model="dialog.form.stuName"></el-input>
                        </el-form-item>
                        <el-form-item label="学号" prop="stuNum">
                            <el-input v-model="dialog.form.stuNum"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号码" prop="phone">
                            <el-input v-model="dialog.form.phone"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" prop="sex">
                            <!-- 传入的性别是0 1 2 -->
                            <el-select v-model="dialog.form.sex">
                                <el-option v-for="item in sexDictList" :key="item.dictValue" :label="dictLabel"
                                    :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="专业" prop="majorId">
                            <el-select v-model="dialog.form.majorId">
                                <el-option v-for="item in majorList" :key="item.majorId" :label="item.majorName"
                                    :value="item.majorId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="年龄" prop="age">
                            <el-input-number v-model="dialog.form.age"></el-input-number>
                        </el-form-item>
                        <el-form-item align="center">
                            <el-button type="primary" @click="handleSubmit">确定</el-button>
                            <el-button type="info" @click="dialog.visible=false,resetForm('dialogForm')">取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { listClasses } from '@/api/classes.js';
import { listStudent, deleteStudent, addStudent, editStudent } from '@/api/student.js';
import { listMajor } from '@/api/major.js';
import { listDict } from '@/api/common.js';
import { query } from '@/utils/common.js'
export default {
    name: "",
    data() {
        return {
            //班级列表
            classesList: [
                {
                    name: "一级1"
                },
                {
                    name: "一级2"
                }
            ],
            //当前班级信息
            curClass: {},

            //学生信息查询
            queryForm: {
                stuNum: undefined,
                stuName: undefined,
                phoneNum: undefined,
            },

            //学生信息列表
            studentList: [
                {
                    stuNum: "1111",
                    stuName: "张三",
                    major: "计科",
                    phone: "123456",
                    age: 18,
                    sex: '0',
                    createTime: "09888",
                    updateTime: "097777",
                },

                {
                    stuNum: "1111",
                    stuName: "张三",
                    major: "计科",
                    phoneNum: "123456",
                    age: 18,
                    sex: '0',
                    createTime: "09888",
                    updateTime: "097777",
                },
            ],

            //专业列表
            majorList: [],
            //性别列表
            sexDictList: [],

            //分页
            pageIniation: {
                pageNum: 1,
                pageSize: 3,//控制每一页显示多少条数据
                total: 0,
            },

            //添加的弹窗
            dialog: {
                mode: "add",//添加学生标志
                visible: false,
                form: {
                    classId: undefined,
                    stuName: undefined,
                    stuNum: undefined,
                    phone: undefined,
                    sex: undefined,
                    majorId: undefined,
                    age: undefined,
                },
                //校验
                rules: {
                    classId: [{ required: true, message: "请选择班级", trigger: "blur" }],
                    stuName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
                    stuNum: [{ required: true, message: "请输入学号", trigger: "blur" }],
                    phone: [{ required: true, message: "请输入手机", trigger: "blur" }],
                    sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
                    majorId: [{ required: true, message: "请选择专业", trigger: "blur" }],
                    age: [{ required: true, message: "请选择年龄", trigger: "blur" }],
                }

            }

        }
    },

    computed: {
        //获取专业
        getMajorName() {
            return majorId => {
                console.log(majorId);
                //将对象结构赋值，获取到专业名称
                const { majorName } = this.majorList.find(major => major.majorId === majorId) || {}
                return majorName || "-"
            }

        },
        //获取性别
        getSexLabel() {
            return (sexCode) => {
                const { dictLabel } = this.sexDictList.find(item => item.dictValue === sexCode) || {}
                return dictLabel || "未知"
            }
        },
    },

    created() {
        this.getListClasses()
        this.getListMajor()
        this.getListDict()

    },
    methods: {
        //获取班级列表信息
        getListClasses() {
            listClasses().then(res => {
                this.classesList = res.data
                this.dialog.form.classId = res.data[0].classId

                if (res.data.length > 0) {
                    //获取到第一个班级信息
                    this.curClass = res.data[0]

                    //默认第一条实现高亮
                    //类似jq的入口函数，等dom更新完之后立马执行回调函数
                    this.$nextTick(() => {
                        this.$refs["classRef"].setCurrentKey(res.data[0].classId)
                    })

                    //学生信息依赖班级信息的接口，所以在获取班级列表里获取学生信息
                    this.getListStudent()
                }


            })
        },

        //获取学生信息
        getListStudent(query = {}) {

            const { classId } = this.curClass
            //过滤掉多余的参数
            const { total, ...rest } = this.pageIniation
            listStudent({ ...rest, classId, ...query }).then(res => {
                this.studentList = res.data.rows
                this.pageIniation.total = res.data.count
            })
        },

        //获取专业列表
        getListMajor() {
            listMajor().then(res => {
                console.log(res);
                this.majorList = res.data

            })

        },
        //获取性别列表
        getListDict() {
            listDict("sys_user_sex").then(res => {
                this.sexDictList = res.data

            })
        },

        //点击班级列表时，更新学生列表
        handleNodeClick(data, node) {

            //获取点击的当前班级信息
            this.curClass = JSON.parse(JSON.stringify(data))
            this.dialog.form.classId = data.classId

            //更新学生信息，再调用一次接口
            this.getListStudent()

        },

        //点击查询,获取到学生信息
        handleQuery() {
            //查询为空(包括空格)时，进行提示，提示先输入值，至少有一个输入框有值：some,用于数组
            const hasInput = query(this.queryForm)
            //符合条件，至少有一项符合
            if (hasInput) return this.getListStudent(this.queryForm)

            //不符合，进行提示
            this.$message.warning("请至少输入一个值！")
        },

        //查询后重置
        resetForm(refName) {
            this.$refs[`${refName}Ref`].resetFields()

        },

        //删除
        handleDelete(row) {
            //提示
            this.$confirm(`是否删除学生【${row.stuName}】？`, "系统提示", {
                type: "warning",
                //确定.then
            }).then(() => {
                deleteStudent(row.stuId).then(res => {
                    this.$message.success(res.msg)
                    //删除后，重新更新学生信息
                    this.getListStudent()
                })
                //取消.catch
            }).catch(() => { })
        },

        //添加
        handleAdd() {
            this.dialog.visible = true
            this.dialog.mode = "add"
        },

        //编辑
        handleEdit(row) {
            this.dialog.visible = true
            this.dialog.mode = "edit"

            //等dom更新之后再执行，解决：点击编辑之后再点添加显示的是编辑的信息的问题
            this.$nextTick(()=>{
            //进行数据回显，信息显现在编辑表单
            this.dialog.form = JSON.parse(JSON.stringify(row))
            })
           
        },

        //确定提交信息
        handleSubmit() {
            //空值提交先进行校验提醒
            this.$refs[`dialogFormRef`].validate(async valid => {

                //检验失败
                if (!valid) return
                //校验成功(判断是添加还是编辑)
                //过滤不需要的参数
                let { createTime, updateTime, classInfo, majorInfo, stuId, ...rest } = this.dialog.form
                let result = {}
                switch (this.dialog.mode) {
                    case "add":
                        try {
                            result = await addStudent({ ...rest })
                        } catch (error) {
                            break;
                        }

                    case "edit":
                        try {
                            result = await editStudent({ ...rest, stuId })
                        } catch (error) {
                            break
                        }
                }

                //提示添加成功
                this.$message.success(result.msg)
                //更新学生信息
                this.getListStudent()
                //关闭弹窗
                this.dialog.visible = false
                //添加后重置表单
                this.resetForm("dialogForm")//this.resetForm(dialog.Form)

            })

        }

    },
}
</script>

<style lang="scss" scoped></style>